﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace ReverseEGNs
{
    class ReverseEGNs
    {
        private static List<string> egns = new List<string>();

        public static List<string> Egns
        {
            get { return ReverseEGNs.egns; }
        }

        static void Main()
        {
            string inputFile = "../../persons.txt";
            string text = ReadFile(inputFile);
            ReplaceEGN(inputFile, text);
        }

        private static string ReadFile(string inputFile)
        {
            string input;
            StreamReader reader = new StreamReader(inputFile);
            using (reader)
            {
                input = reader.ReadToEnd();
                ExtractEGN(input);
            }
            return input;
        }

        public static void ExtractEGN(string input)
        {
            Regex patern = new Regex(@"\D(?<egn>[\d]{10})\D");
            Match m = patern.Match(input);
            while (m.Success)
            {
                Group group = m.Groups["egn"];
                egns.Add(group.ToString());
                m = m.NextMatch();
            }
        }

        private static void ReplaceEGN(string inputFile, string text)
        {
            StreamWriter writer = new StreamWriter(inputFile);
            using (writer)
            {
                foreach (string egn in egns)
                {
                    string reverseEGN = ReverseEGN(egn);
                    Regex patern = new Regex(egn);
                    text = patern.Replace(text, reverseEGN);
                }
                writer.Write(text);
            }
        }

        private static string ReverseEGN(string egn)
        {
            string result = "";
            for (int i = egn.Length-1; i > -1; i--)
            {
                result += egn[i];
            }
            return result;
        }
    }
}
